package com.yyf.blogapi.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yyf.blogapi.common.log.LogAnnotation;
import com.yyf.blogapi.po.SysUser;
import com.yyf.blogapi.service.ISysUserService;
import com.yyf.blogapi.util.JwtUtil;
import com.yyf.blogapi.common.ErrorCode;
import com.yyf.blogapi.vo.LoginParam;
import com.yyf.blogapi.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class AccountController {

    @Value("${md5.salt}")
    private String salt;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @LogAnnotation(module = "用户",operation = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginParam loginParam) {
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        //首先校验用户名和密码是不是为空
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        //对密码进行md5加密
        //去数据库查找
        SysUser user = sysUserService.getUserByAccountAndPassword(account, DigestUtils.md5Hex(password + salt));
        //数据库没有的话
        if (user == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        //异步去更新最后登录时间
        sysUserService.updateLastLogin(user);
        String token = jwtUtil.generateToken(user.getId());
        redisTemplate.opsForValue().set("userId_" + user.getId(), token, 1, TimeUnit.DAYS);
        log.info(String.valueOf(jwtUtil.getClaims(token).getIssuedAt()));
        log.info(String.valueOf(jwtUtil.getClaims(token).getExpiration()));

        return Result.success(token);
    }

    @LogAnnotation(module = "用户",operation = "校验token，返回用户信息")
    @GetMapping("/users/currentUser")
    public Result currentUser(@RequestHeader("Authorization") String token) {

        SysUser user = sysUserService.checkToken(token);

        if (user==null){
            return Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
        }
        return Result.success(user);
    }

    @LogAnnotation(module = "用户",operation = "退出")
    @GetMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token) {
        redisTemplate.delete("userId_" + jwtUtil.getClaims(token).get("userId"));
        return Result.success(null);
    }

    @LogAnnotation(module = "用户",operation = "注册")
    @PostMapping("/register")
    public Result register(@RequestBody LoginParam loginParam) {
        //首先校验用户名和密码是不是为空
        if (StringUtils.isBlank(loginParam.getAccount())
                || StringUtils.isBlank(loginParam.getPassword())
                || StringUtils.isBlank(loginParam.getNickname())) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        //看是否已注册
        SysUser user = sysUserService.getUserByAccount(loginParam.getAccount());
        if (user != null) {
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_EXIST.getMsg());
        }

        return Result.success(sysUserService.register(loginParam));
    }
}
